<template>
  <div>
    <div>
      <v-snackbar v-model="isSuccess" :timeout="3000" top style="color: #68c23c;" color="#f0f9eb">
        {{ text }}
      </v-snackbar>
      <v-snackbar v-model="isError" :timeout="3000" top class="custom-alert-error" color="#fef0f0">
        {{ text }}
      </v-snackbar>
    </div>
    <v-dialog v-model="dialog" persistent transition="fab-transition" max-width="800" id="settings">
      <v-card tile>
        <div class="d-flex justify-space-between mb-5" id="modal-header">
          <v-card-title class="py-3">设置</v-card-title>

          <v-btn icon text @click="closeModal">
            <v-icon>mdi-close</v-icon>
          </v-btn>
        </div>

        <v-card-text>
          <v-row>
            <v-col order="last" order-sm="last" order-md="first" order-lg="first" order-xl="first" cols="12" sm="12"
              md="8" lg="8" class="pt-0">
              <h3 class="mb-6 mt-0 pt-0"></h3>
              <ValidationObserver ref="personalInfoForm" v-slot="{ handleSubmit, reset }">
                <form @submit.prevent="handleSubmit(submit)" @reset.prevent="reset">
                  <ValidationProvider v-slot="{ errors }" name="昵称" rules="required|min:3">
                    <v-text-field v-model="formData.nickName" :error-messages="errors" label="昵称" filled
                      dense></v-text-field>
                  </ValidationProvider>
                  <ValidationProvider v-slot="{ errors }" name="邮箱" rules="required|email">
                    <v-text-field v-model="formData.email" :error-messages="errors" label="邮箱" filled
                      dense></v-text-field>
                  </ValidationProvider>
                  <ValidationProvider v-slot="{ errors }" name="个性签名" rules="required|min:3">
                    <v-text-field v-model="formData.personalSignature" :error-messages="errors" label="个性签名" filled
                      dense></v-text-field>
                  </ValidationProvider>
                  <v-btn :loading="loading.personalInfo" type="submit" class="primary " depressed>提交</v-btn>
                </form>
              </ValidationObserver>

              <h3 class="mb-6 mt-6">修改密码</h3>
              <ValidationObserver ref="passwordForm" v-slot="{ handleSubmit, reset }">
                <form @submit.prevent="handleSubmit(submitPassword)" @reset.prevent="reset">
                  <ValidationProvider v-slot="{ errors }" name="原密码" rules="required|min:6">
                    <v-text-field v-model="formData.currentPassword" :append-icon="showCurrentPassword ? 'mdi-eye' : 'mdi-eye-off'
                      " :error-messages="errors" :type="showCurrentPassword ? 'text' : 'password'" name="原密码" label="原密码"
                      filled dense hint="至少需要6位字符" class="input-group--focused"
                      @click:append="showCurrentPassword = !showCurrentPassword"></v-text-field>
                  </ValidationProvider>
                  <ValidationProvider v-slot="{ errors }" name="新密码" rules="required|min:6">
                    <v-text-field v-model="formData.newPassword"
                      :append-icon="showNewPassword ? 'mdi-eye' : 'mdi-eye-off'" :error-messages="errors"
                      :type="showNewPassword ? 'text' : 'password'" name="新密码" label="新密码" filled dense
                      hint="至少需要6位字符" class="input-group--focused"
                      @click:append="showNewPassword = !showNewPassword"></v-text-field>
                  </ValidationProvider>

                  <v-btn :loading="loading.password" type="submit" class="primary" depressed>修改</v-btn>
                </form>
              </ValidationObserver>
            </v-col>
            <v-col order-sm="1" cols="12" sm="12" md="4" lg="4" class="text-center">
              <v-btn text @click="toggleShow">上传头像</v-btn>
              <div v-if="show">
                <v-file-input v-model="selectedFile" label="选择文件" placeholder="没有选择文件"  accept="image/png,image/jpeg"></v-file-input>
                <v-btn @click="uploadFile">上传</v-btn>
                <p v-if="uploadProgress !== null">上传进度: {{ uploadProgress }}%</p>
                <p v-if="successMessage">{{ successMessage }}</p>
              </div>
              <!-- <my-upload
              field="avatar"
              method="GET"
              :headers="headers"
              @crop-success="cropSuccess"
              @crop-upload-success="cropUploadSuccess"
              @crop-upload-fail="cropUploadFail"
              v-model="show"
              :url="url"
              :width="200"
              :height="200"
              :noRotate="false" 
              img-format="jpg"
              langType="zh"
            ></my-upload> -->
              <v-responsive width="230" class="mx-auto" style="border-radius: 50%;">
                <div v-if="$store.getters.currentUser.avatar == 'no-photo.jpg'" class="px-12"
                  id="settings-image-placeholder">
                  <v-icon>mdi-image-plus</v-icon>
                </div>
                <v-img v-else height="220" :src="imgDataUrl"></v-img>
              </v-responsive>
            </v-col>
          </v-row>
        </v-card-text>
      </v-card>
    </v-dialog>
  </div>

</template>

<script>
//import myUpload from 'vue-image-crop-upload'
import { resetPassword, updateUser } from '../services/UserRequest';
import axios from "axios";
export default {
  name: 'SettingsModal',
  props: ['openDialog'],
  data: function () {
    return {
      text: '',
      isSuccess: false,
      isError: false,
      selectedFile: null,
      successMessage: null,
      showCurrentPassword: false,
      showNewPassword: false,
      valid: false,
      interval: {},
      value: 0,
      show: false,
      rules: [
        (value) =>
          !value ||
          value.size < 5000000 ||
          'Video size should be less than 5 MB!'
      ],
      formData: {
        personalSignature: this.$store.getters.currentUser.personalSignature,
        userId: this.$store.getters.currentUser.userId,
        nickName: this.$store.getters.currentUser.nickName,
        email: this.$store.getters.currentUser.email,
        currentPassword: '',
        newPassword: ''
      },
      loading: {
        personalInfo: false,
        password: false
      },
      uploadProgress: null,

      imgDataUrl: this.$store.getters.currentUser.avatar,
      url: 'http://127.0.0.1:8080/echo/user/avatar/stream',
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        Authorization: this.$store.getters.getToken
      }
    }
  },
  computed: {
    dialog() {
      return this.openDialog
    }
  },
  methods: {
    async submit() {
      if (this.loading.personalInfo) return
      this.loading.personalInfo = true

      const user = await updateUser(this.formData)
        .catch(() => {
          this.loading.personalInfo = false
          this.isError = true
          this.text = '服务器异常'
        })
        .finally(() => (this.loading.personalInfo = false))

      if (!user) return
      this.text = user.data.message
      if (user.data.code == 200) {
        this.isSuccess = true
      }
      if (user.data.code == 500) {
        this.isError = true
        return
      }
      this.$store.getters.currentUser.nickName = this.formData.nickName
      this.$store.getters.currentUser.email = this.formData.email
      this.$store.getters.currentUser.personalSignature = this.formData.personalSignature
      await this.$store
        .dispatch('getCurrentUser')
        .catch((err) => console.log(err))
      window.location.reload()
      this.closeModal()
    },
    async uploadFile() {
      const formData = new FormData();
      formData.append("avatar", this.selectedFile);
      axios.post("/api/echo/user/avatar", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
          "Authorization": localStorage.getItem("Authorization")
        },
        onUploadProgress: progressEvent => {
          this.uploadProgress = Math.round(
            (progressEvent.loaded / progressEvent.total) * 100
          );
        }
      })
        .then((res) => {
          this.successMessage = "头像上传成功!";
          this.selectedFile = null;
          this.uploadProgress = null;
          console.log(res)
          this.imgDataUrl = res.data
          this.$store.getters.currentUser.avatar = res.data
        })
        .catch(() => {
          this.successMessage = "头像上传失败!";
          this.uploadProgress = null;
        });
    },
    async submitPassword() {
      if (this.loading.password) return

      this.loading.password = true

      const user = await resetPassword({
        userId: this.$store.getters.currentUser.userId,
        newPassword: this.formData.newPassword,
        currentPassword: this.formData.currentPassword
      })
        .catch(() => {
          this.loading.password = false
          this.text = '服务异常'
          this.isError = true
        })
        .finally(() => (this.loading.password = false))
      if (!user) return
      this.text = user.data.message

      if(user.data.code==200){
        this.isSuccess = true
      }else{
        this.isError = true
        return
      }
      this.formData.currentPassword = ''
      this.formData.newPassword = ''
      this.closeModal()

      this.$store.dispatch('signOut')
      this.$router.push('/signin')
    },
    closeModal() {
      this.$emit('closeDialog')
    },

    toggleShow() {
      this.show = !this.show
    }
  },
  components: {

  }
}
</script>

<style lang="scss">
.custom-alert {
  color: #68c23c;
  /* 深绿色文字 */
}

.custom-alert-error {
  color: #f56c6c;
}
#modal-header {
  border-bottom: 1px solid rgb(238, 232, 232);
}

#settings-image-placeholder {
  padding-top: 7em;
  padding-bottom: 7em;
  border: 2px dashed rgb(209, 209, 209);
  border-radius: 50%;
}

@media (max-width: 700px) {
  .vue-image-crop-upload {
    .vicp-wrap {
      width: 95%;
      height: 550px;

      .vicp-step2 .vicp-crop {
        .vicp-crop-left {
          float: none;

          .vicp-range {
            margin: auto;
            margin-top: 30px;
          }

          & * {
            margin-left: auto;
            margin-right: auto;
          }
        }

        .vicp-crop-right {
          float: none;
          margin-top: 30px;

          .vicp-preview .vicp-preview-item {
            display: inline-block;
            float: none;
          }

          & * {
            // margin-left: auto;
            // margin-right: auto;
          }
        }
      }
    }
  }
}
</style>
